package com.atguigu.test01;

import java.sql.*;

/**
 * @author haoranlu
 * @project IntelliJ IDEA
 * 人如何让PreparedStatement执行完insert的sql语句后带回自增长的键值？
 * (1)在创建PreparedStatement是就应该指明需要返回自增长的键值，否则ysql服务器不会返回这个键值
 *  PreparedStatement pst = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
 *  (2)通过拿到结果集来获取自动增长的键值
 *  但是方法不要调用getResultSet()来获取，不然会返回空指针异常
 *  使用getGeneratedKeys();
 */
public class TestGenerateKey {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.jdbc.Driver");

        String url = "jdbc:mysql://localhost:3306/test";
        Connection conn = DriverManager.getConnection(url, "root", "123456");

        String sql = "insert into t_department values(null,?,?)";

        PreparedStatement pst = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);

        pst.setString(1,"发钱部门");
        pst.setString(2,"xxxxx");

        int len = pst.executeUpdate();
        System.out.println(len>=0?"添加成功":"添加失败");

        //ResultSet rs = pst.getResultSet();
        //mysql服务器通过结果集把自增长的键值返回回来
        ResultSet rs = pst.getGeneratedKeys();
        if (rs.next()){
            System.out.println("新的部门编号:"+rs.getObject(1));
        }
        rs.close();
        pst.close();
        conn.close();
    }
}









